﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;
using WHC.OrderWater.Commons;


namespace WHC.Hotel.UI
{
    public partial class FrmAddKTVConsume : BaseForm
    {
        public KTVSuiteInfo RoomInfo = null;
        private KTVOrderInfo orderInfo = null;
        private List<KTVConsumerListInfo> consumerList = new List<KTVConsumerListInfo>();
        private decimal amountMoney = 0.0M;

        public FrmAddKTVConsume()
        {
            InitializeComponent();
        }

        private void FrmAddConsume_Load(object sender, EventArgs e)
        {
            this.txtName.Focus();
            if (RoomInfo != null)
            {
                orderInfo = BLLFactory<KTVOrder>.Instance.GetCurrentOrder(RoomInfo.RoomNo);
                if (orderInfo != null)
                {
                    this.lblRoomNo.Text = RoomInfo.RoomNo;
                    this.groupConsumeList.Text = string.Format("{0} {1}",
                        RoomInfo.RoomNo, this.groupConsumeList.Text);

                    ShowGoodListView();
                    ShowGoodsTreeView();
                    BindData();
                }
            }
        }

        private void BindData()
        {
            amountMoney = OnShowStatus(RoomInfo);
            this.lblAmount.Text = string.Format("消费总金额：{0:C}", amountMoney);
        }

        private decimal OnShowStatus(KTVSuiteInfo roomInfo)
        {
            decimal allMoney = 0.0M;

            #region 更新消费记录
            if (roomInfo != null)
            {
                List<KTVConsumerListInfo> consumerList = BLLFactory<KTVSuite>.Instance.GetAllConsumption(roomInfo.RoomNo);

                this.lvwDetail.Items.Clear();
                int i = 1;
                foreach (KTVConsumerListInfo info in consumerList)
                {
                    ListViewItem item = new ListViewItem(info.RoomNo);
                    item.SubItems.Add(info.ItemName);
                    item.SubItems.Add(info.Price.ToString("C2"));
                    item.SubItems.Add(info.Discount.ToString());
                    item.SubItems.Add(info.Quantity.ToString());
                    item.SubItems.Add(info.Amount.ToString("C2"));
                    item.SubItems.Add(info.BeginTime.ToString());
                    item.SubItems.Add(info.Waiter);
                    item.SubItems.Add(info.Creator);
                    item.Tag = info;
                    if (info.Quantity < 0)
                    {
                        item.ForeColor = Color.Red;
                    }

                    this.lvwDetail.Items.Add(item);
                    allMoney += info.Amount;
                    i++;
                }
            }
            #endregion

            this.amountMoney = allMoney;
            return allMoney;
        }

        private void ShowGoodListView()
        {
            #region 项目信息列表

            this.lvwGoods.Items.Clear();
            List<KTVGoodsInfo> goodsList = new List<KTVGoodsInfo>();
            if (this.txtName.Text.Length > 0)
            {
                goodsList = BLLFactory<KTVGoods>.Instance.FindByName(this.txtName.Text);
            }
            else
            {
                goodsList = BLLFactory<KTVGoods>.Instance.GetAll();
            }

            foreach (KTVGoodsInfo info in goodsList)
            {
                ListViewItem item = new ListViewItem(info.ItemNo);
                item.SubItems.Add(info.Name);
                item.SubItems.Add(info.Price.ToString("C2"));
                item.SubItems.Add(info.StockQuantity.ToString());

                item.Tag = info;
                this.lvwGoods.Items.Add(item);
            }

            #endregion
        }

        private void ShowGoodsTreeView()
        {
            #region 项目类型信息明细类别

            this.treeGoods.Nodes.Clear();
            this.treeGoods.BeginUpdate();

            List<KTVGoodsTypeInfo> typeList = BLLFactory<KTVGoodsType>.Instance.GetAll();
            foreach (KTVGoodsTypeInfo info in typeList)
            {
                TreeNode typeNode = new TreeNode(info.GoodsType, 0, 0);
                this.treeGoods.Nodes.Add(typeNode);
                //typeNode.Tag = info;

                List<KTVGoodsInfo> goods = BLLFactory<KTVGoods>.Instance.FindByGoodsType(info.GoodsType);
                foreach (KTVGoodsInfo goodInfo in goods)
                {
                    string display = string.Format("{0}   {1}", goodInfo.Name, goodInfo.Price);
                    TreeNode subNode = new TreeNode(display, 1, 1);
                    subNode.Tag = goodInfo;
                    typeNode.Nodes.Add(subNode);
                }
            }
            this.treeGoods.EndUpdate();
            this.treeGoods.ExpandAll();

            #endregion
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            ShowGoodListView();

            if (this.lvwGoods.Items.Count > 0)
            {
                ListViewItem item = this.lvwGoods.Items[0];
                if (item != null)
                {
                    KTVGoodsInfo info = item.Tag as KTVGoodsInfo;
                    TreeNode node = FindNode(info.ID);
                    this.treeGoods.ExpandAll();
                    this.treeGoods.SelectedNode = node;
                }
            }
        }

        private TreeNode FindNode(int goodId)
        {
            foreach (TreeNode typeNode in this.treeGoods.Nodes)
            {
                foreach (TreeNode node in typeNode.Nodes)
                {
                    if (node.Tag != null)
                    {
                        KTVGoodsInfo goodsInfo = node.Tag as KTVGoodsInfo;
                        if (goodsInfo != null && 
                            goodsInfo.ID.ToString() == goodId.ToString())
                        {
                            return node;
                        }
                    }
                }
            }
            return null;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.lvwGoods.SelectedItems.Count > 0)
            {
                ListViewItem item = this.lvwGoods.SelectedItems[0];//按钮默认加第一个
                KTVGoodsInfo info = item.Tag as KTVGoodsInfo;
                int count = Convert.ToInt32(this.txtQuantity.Text);
                if (info != null)
                {
                    InsertOnItem(info);
                }
                BindData();             
            }
        }

        private void lvwGoods_DoubleClick(object sender, EventArgs e)
        {
            foreach(ListViewItem item in this.lvwGoods.SelectedItems)
            {
                KTVGoodsInfo info = item.Tag as KTVGoodsInfo;
                
                if (info != null)
                {
                    InsertOnItem(info);
                }
            }
            BindData();
        }

        private void InsertOnItem(KTVGoodsInfo info)
        {
            #region 构造消费信息
            int count = Convert.ToInt32(this.txtQuantity.Text);
            KTVConsumerListInfo consumeInfo = new KTVConsumerListInfo();
            consumeInfo.Amount = info.Price * count;
            consumeInfo.BeginTime = DateTime.Now;
            consumeInfo.Creator = Portal.gc.LoginInfo.FullName;
            consumeInfo.Discount = 1.0;
            consumeInfo.DiscountPrice = info.Price;
            consumeInfo.EndTime = DateTime.Now;
            consumeInfo.ItemType = info.GoodsType;
            consumeInfo.ItemName = info.Name;
            consumeInfo.ItemNo = info.ItemNo;
            consumeInfo.Price = info.Price;
            consumeInfo.Quantity = count;
            consumeInfo.RoomNo = RoomInfo.RoomNo;
            consumeInfo.Waiter = "*";
            consumeInfo.Order_ID = orderInfo.ID;
            #endregion

            BLLFactory<KTVConsumerList>.Instance.Insert(consumeInfo);
            BLLFactory<KTVGoods>.Instance.AddStockQuantiy(consumeInfo.ItemNo, consumeInfo.ItemName, -Convert.ToInt32(consumeInfo.Quantity));
            this.txtQuantity.Text = "1";//还原为1
        }

        private void treeGoods_DoubleClick(object sender, EventArgs e)
        {
            TreeNode node = this.treeGoods.SelectedNode;
            if (node.Tag != null)
            {
                KTVGoodsInfo info = node.Tag as KTVGoodsInfo;
                if (info != null)
                {
                    InsertOnItem(info);
                }
                BindData();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void lvwDetail_Click(object sender, EventArgs e)
        {
            if (this.lvwDetail.SelectedItems.Count == 0) return;

            ListViewItem item = this.lvwDetail.SelectedItems[0];
            KTVConsumerListInfo info = item.Tag as KTVConsumerListInfo;
            if (info != null)
            {
                this.btnTransfer.Enabled = (info.ItemName != "房间费" && info.ItemName != "最低消费补差");
                this.btnTransferRoom.Enabled = (info.ItemName != "房间费" && info.ItemName != "最低消费补差");
                this.btnDelete.Enabled = info.Quantity > 0;
            }
        }

        private void lvwDetail_DoubleClick(object sender, EventArgs e)
        {
            btnDelete_Click(null, null);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            //消费退单
            if (this.lvwDetail.SelectedItems.Count == 0) return;

            ListViewItem item = this.lvwDetail.SelectedItems[0];
            KTVConsumerListInfo info = item.Tag as KTVConsumerListInfo;
            if (info != null && info.Quantity > 0)
            {
                FrmBackKTVOrder dlg = new FrmBackKTVOrder();
                dlg.lblAllowCount.Text = info.Quantity.ToString();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    #region 实现退单
                    try
                    {
                        int backCount = Convert.ToInt32(dlg.txtBackCount.Text);
                        string reason = dlg.txtReason.Text;
                        info.Order_ID = orderInfo.ID;//修改订单ID

                        bool success = BLLFactory<KTVSuite>.Instance.BackConsumption(info,
                            backCount, reason);
                        if (success)
                        {
                            BLLFactory<KTVGoods>.Instance.AddStockQuantiy(info.ItemNo, info.ItemName, backCount);
                            MessageUtil.ShowTips("退单成功");
                        }
                        else
                        {
                            MessageUtil.ShowWarning("退单失败");
                        }

                        OnShowStatus(RoomInfo);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        MessageUtil.ShowError(ex.Message);
                    }
                    #endregion
                }
                BindData();
            }
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            //消费转单
            if (this.lvwDetail.SelectedItems.Count == 0) return;

            ListViewItem item = this.lvwDetail.SelectedItems[0];
            KTVConsumerListInfo info = item.Tag as KTVConsumerListInfo;
            if (info != null)
            {
                FrmKTVTransferOrder dlg = new FrmKTVTransferOrder();
                dlg.lblAmount.Text = info.Amount.ToString("C2");
                dlg.lblItemName.Text = info.ItemName;
                dlg.lblRoomNo.Text = RoomInfo.RoomNo;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    #region 实现转单
                    try
                    {
                        bool success = BLLFactory<KTVSuite>.Instance.TransferConsumption(dlg.txtTargetRoom.Text, RoomInfo.RoomNo, info);
                        if (success)
                        {
                            MessageUtil.ShowTips("转单成功");
                        }
                        else
                        {
                            MessageUtil.ShowWarning("转单失败");
                        }

                        OnShowStatus(RoomInfo);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        MessageUtil.ShowError(ex.Message);
                    } 
                    #endregion
                }
                BindData();
            }
        }

        private void btnTransferRoom_Click(object sender, EventArgs e)
        {
            //消费转单
            if (this.lvwDetail.SelectedItems.Count == 0) return;

            ListViewItem item = this.lvwDetail.SelectedItems[0];
            KTVConsumerListInfo info = item.Tag as KTVConsumerListInfo;
            if (info != null)
            {
                FrmTransferOtherOrder dlg = new FrmTransferOtherOrder();
                dlg.lblAmount.Text = info.Amount.ToString("C2");
                dlg.lblItemName.Text = info.ItemName;
                dlg.lblRoomNo.Text = RoomInfo.RoomNo;
                dlg.lblCurrentRoom.Text = "当前包间";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    #region 实现转单
                    try
                    {
                        bool success = BLLFactory<Room>.Instance.TransferKTVConsumption(dlg.txtTargetRoom.Text, RoomInfo.RoomNo, info);
                        if (success)
                        {
                            MessageUtil.ShowTips("转单到客房成功");
                        }
                        else
                        {
                            MessageUtil.ShowWarning("转单到客房失败");
                        }

                        OnShowStatus(RoomInfo);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        MessageUtil.ShowError(ex.Message);
                    }
                    #endregion
                }
                BindData();
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (this.lvwDetail.Items.Count == 0)
            {
                MessageUtil.ShowTips("没有消费记录");
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}\r\n\r\n", Portal.gc.gAppUnit);
            sb.AppendFormat("包 间 号：{0}\r\n", RoomInfo.RoomNo);
            sb.AppendFormat("打印时间：{0}\r\n\r\n", DateTime.Now);

            sb.AppendFormat("项目     单价  数量  金额\r\n");
            for (int i = 0; i < lvwDetail.Items.Count; i++)
            {
                ListViewItem item = lvwDetail.Items[i];
                sb.AppendFormat("{0}", item.SubItems[1].Text);
                sb.AppendFormat(" {0}", item.SubItems[2].Text);
                sb.AppendFormat(" {0}", item.SubItems[4].Text);
                sb.AppendFormat(" {0}\r\n", item.SubItems[5].Text);
            }
            sb.AppendFormat("\r\n\r");
            sb.AppendFormat("总金额：{0}\r\n", amountMoney.ToString("C2"));
            sb.AppendFormat("大  写：{0}\r\n", RMBUtil.CmycurD(amountMoney));
            sb.AppendFormat("\r\n\r");

            Portal.gc.PosPrint(sb.ToString());
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnAdd_Click(null, null);
            }
        }

        private void btnGift_Click(object sender, EventArgs e)
        {
            //消费转单
            if (this.lvwDetail.SelectedItems.Count == 0) return;

            if (MessageUtil.ShowYesNoAndTips("您确定要赠送此单么？") == DialogResult.Yes)
            {
                ListViewItem item = this.lvwDetail.SelectedItems[0];
                KTVConsumerListInfo info = item.Tag as KTVConsumerListInfo;
                if (info != null)
                {
                    info.ItemName += "(赠)";
                    info.Discount = 0;
                    info.DiscountPrice = 0M;
                    info.Amount = 0M;

                    BLLFactory<KTVConsumerList>.Instance.Update(info, info.ID.ToString());
                }
                BindData();
            }
        }
        private void menuAdd_Add_Click(object sender, EventArgs e)
        {
            btnAdd_Click(null, null);
        }

        private void menuAdd_Send_Click(object sender, EventArgs e)
        {
            if (this.lvwGoods.SelectedItems.Count > 0)
            {
                ListViewItem item = this.lvwGoods.SelectedItems[0];//按钮默认加第一个
                KTVGoodsInfo info = item.Tag as KTVGoodsInfo;
                int count = Convert.ToInt32(this.txtQuantity.Text);
                if (info != null)
                {
                    InsertAsGiftItem(info);
                }
                BindData();
            }
        }
        private void InsertAsGiftItem(KTVGoodsInfo info)
        {
            #region 构造消费信息
            int count = Convert.ToInt32(this.txtQuantity.Text);
            KTVConsumerListInfo consumeInfo = new KTVConsumerListInfo();
            consumeInfo.Amount = 0;
            consumeInfo.BeginTime = DateTime.Now;
            consumeInfo.Creator = Portal.gc.LoginInfo.FullName;
            consumeInfo.Discount = 0;
            consumeInfo.DiscountPrice = 0;
            consumeInfo.EndTime = DateTime.Now;
            consumeInfo.ItemName = info.Name + "(赠)";
            consumeInfo.ItemType = info.GoodsType;
            consumeInfo.ItemNo = info.ItemNo;
            consumeInfo.Price = info.Price;
            consumeInfo.Quantity = count;
            consumeInfo.RoomNo = RoomInfo.RoomNo;
            consumeInfo.Waiter = "*";
            consumeInfo.Order_ID = orderInfo.ID;
            #endregion

            BLLFactory<KTVConsumerList>.Instance.Insert(consumeInfo);
        }
    }
}
